package com.macro.mall.tiny.modules.pms.controller;


import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.macro.mall.tiny.common.api.CommonResult;
import com.macro.mall.tiny.common.api.ResultCode;
import com.macro.mall.tiny.modules.pms.model.PmsCategory;
import com.macro.mall.tiny.modules.pms.model.PmsErrorCase;
import com.macro.mall.tiny.modules.pms.service.PmsCategoryService;
import com.macro.mall.tiny.modules.pms.service.PmsErrorCaseService;
import com.macro.mall.tiny.modules.pms.service.PmsUserActionService;
import com.macro.mall.tiny.modules.pms.vo.PmsErrorCaseVO;
import com.macro.mall.tiny.security.util.MemberContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author tyrone
 * @since 2024-10-09
 */
@RestController
@RequestMapping("/pms/pmsErrorCase")
@Api(tags = "PmsErrorCaseController")
@Tag(name = "PmsErrorCaseController", description = "故障现象")
public class PmsErrorCaseController {

    @Autowired
    private PmsErrorCaseService pmsErrorCaseService;
    @Autowired
    private PmsCategoryService pmsCategoryService;

    @ApiOperation("获取故障现象分类")
    @GetMapping("/getErrorCaseCategory")
    public CommonResult<List<PmsErrorCaseVO>> getErrorCaseCategory() {
        List<PmsErrorCaseVO> result = pmsErrorCaseService.getErrorCaseCategory();
        Map<Integer, PmsCategory> collect = pmsCategoryService.list().stream().collect(Collectors.toMap(PmsCategory::getId, category -> category));
        for (PmsErrorCaseVO pmsErrorCaseVO : result) {
            pmsErrorCaseVO.setIcon(collect.get(pmsErrorCaseVO.getCategoryId()).getIcon());
        }
        return CommonResult.success(result);
    }


    @ApiOperation("根据分类ID获取故障现象")
    @GetMapping("/getErrorCaseByCategoryId")
    public CommonResult<List<String>> getErrorCaseByCategoryId(Integer categoryId) {
        List<PmsErrorCase> list = pmsErrorCaseService.list(new QueryWrapper<PmsErrorCase>()
                .select("error_case")
                .eq("category_id", categoryId).groupBy("error_case"));
        if (ObjectUtils.isEmpty(list)) {
            return CommonResult.success(Collections.emptyList());
        }
        return CommonResult.success(list.stream().map(PmsErrorCase::getErrorCase).collect(Collectors.toList()));
    }

    @ApiOperation("获取故障现象详情")
    @GetMapping("/getDetailErrorCase")
    public CommonResult<List<PmsErrorCase>> getDetailErrorCase(
            @RequestParam Integer categoryId,
            @RequestParam String errorCase) {
        if (MemberContext.getMember() == null) {
            return CommonResult.failed(ResultCode.UNAUTHORIZED);
        }
        if (MemberContext.getMember().getVip() == null || MemberContext.getMember().getVip().equals(0)) {
            return CommonResult.failed(ResultCode.NEED_VIP);
        }
        List<PmsErrorCase> list = pmsErrorCaseService.list(new QueryWrapper<PmsErrorCase>()
                .eq("category_id", categoryId)
                .eq("error_case", errorCase));
        if (ObjUtil.isEmpty(list)) {
            return CommonResult.success(Collections.emptyList());
        }
        handlePrivacyData(list);
        return CommonResult.success(list);
    }

    @ApiOperation("（前后台通用）分页获取故障现象（万能接口） 支持id、errorCase、categoryId、content、title ")
    @PostMapping("page")
    public CommonResult<IPage<PmsErrorCase>> listErrorCase(@RequestBody PmsErrorCase pmsErrorCode
            , @ApiParam(defaultValue = "1") @RequestParam Integer pageNum, @ApiParam(defaultValue = "10") @RequestParam Integer pageSize) {
        if (pageNum == null) pageNum = 1;
        if (pageSize == null) pageSize = 10;
        QueryWrapper<PmsErrorCase> query = new QueryWrapper<>();
        if (pmsErrorCode.getId() != null) query.eq("id", pmsErrorCode.getId());
        if (StringUtils.isNotEmpty(pmsErrorCode.getErrorCase())) query.like("error_case", pmsErrorCode.getErrorCase());
        if (pmsErrorCode.getCategoryId() != null) query.eq("category_id", pmsErrorCode.getCategoryId());
        if (StringUtils.isNotEmpty(pmsErrorCode.getContent())) query.like("content", pmsErrorCode.getContent());
        if (StringUtils.isNotEmpty(pmsErrorCode.getTitle())) query.like("title", pmsErrorCode.getTitle());
        Map<Integer, PmsCategory> collect = pmsCategoryService.list().stream().collect(Collectors.toMap(PmsCategory::getId, category -> category));

        IPage<PmsErrorCase> result = pmsErrorCaseService.page(new Page<>(pageNum, pageSize, true), query);
        if (!result.getRecords().isEmpty()) {
            result.getRecords().forEach(e -> e.setCategoryName(collect.get(e.getCategoryId()).getName()));
        }
        handlePrivacyData(result.getRecords());
        return CommonResult.success(result);

    }

    @ApiOperation("后台添加故障现象")
    @PostMapping("/add")
    public CommonResult<Void> addErrorCase(@RequestBody PmsErrorCase pmsErrorCase) {
        pmsErrorCaseService.save(pmsErrorCase);
        return CommonResult.success(null);
    }

    @ApiOperation("后台修改故障现象")
    @PutMapping("/update")
    public CommonResult<Void> updateErrorCase(@RequestBody PmsErrorCase pmsErrorCase) {
        pmsErrorCaseService.updateById(pmsErrorCase);
        return CommonResult.success(null);
    }

    @ApiOperation("后台批量删除故障现象")
    @DeleteMapping("/delete")
    public CommonResult<Void> deleteErrorCase(@RequestParam("ids") List<Integer> ids) {
        pmsErrorCaseService.removeByIds(ids);
        return CommonResult.success(null);
    }

    @Autowired
    private PmsUserActionService pmsUserActionService;

    private void handlePrivacyData(List<PmsErrorCase> lists) {
        if (MemberContext.getMember() != null) {
            List<Object> objects = pmsUserActionService.listItem(1, 0);
            for (PmsErrorCase errorCase : lists) {
                if (objects.contains(errorCase.getId())) {
                    errorCase.setCurrentMemberLike(1);
                } else {
                    errorCase.setCurrentMemberLike(0);
                }
            }
        }
    }

}

